/*
 * @Description: 日志管理reducer
 * @Author: Rfan
 * @Date: 2022-09-19 14:08:51
 * @LastEditTime: 2022-09-19 17:47:51
 */

import { jsonClone } from '@/utils';
import { delItemByIdArray } from '@/utils/list';
import {
  SET_LOG_LIST,
  DELETE_LOG_ITEM,
  SET_SELECTED_ITEM,
  SET_SELECT_LOG_CLASS,
  DELETE_LOG_ORIGIN,
  SET_LOG_TYPE,
  SET_EXPORT_COLS,
  SET_LIST_CONDITION,
  INIT_LIST_CONDITION
} from '../constants';

export const LogReducer = (state, action) => {
  switch (action.type) {
    /**
     * @description: 设置日志单类型
     */
    case SET_LOG_TYPE:
      return {
        ...state,
        logType: action.data
      };

    /**
     * @description: 设置选中的日志单类别
     */
    case SET_SELECT_LOG_CLASS:
      return {
        ...state,
        selectLogNav: action.data
      };

    /**
     * @description: 设置选中的日志单类别
     */
    case INIT_LIST_CONDITION:
      return {
        ...state,
        listCondition: action.data
      };

    /**
     * @description: 设置选中的日志单类别
     */
    case SET_LIST_CONDITION:
      return {
        ...state,
        listCondition: { ...state.listCondition, ...action.data }
      };

    /**
     * @description: 保存表格选中的条目id
     * @param {number[]} data
     */
    case SET_SELECTED_ITEM:
      return { ...state, selectItems: action.data };

    /**
     * @description: 设置导出表格的表头
     * @param {any[]} data
     */
    case SET_EXPORT_COLS:
      return { ...state, exportCols: action.data };

    /**
     * @description: 设置日志单列表
     * @param {Array} data 日志单列表
     */
    case SET_LOG_LIST: {
      return {
        ...state,
        logList: action.data
      };
    }

    /**
     * @description: 删除日志单条目原文
     * @param {number[]} ids 删除的ID列表
     */
    case DELETE_LOG_ORIGIN: {
      const logList = jsonClone(state.logList);
      if (action.ids instanceof Array) {
        logList.forEach((item) => {
          if (action.ids.indexOf(item.id) < 0) {
            item.logInfo.deleted = 1;
          }
        });
      } else {
        logList.forEach((item) => {
          if (item.id === action.ids) {
            item.logInfo.deleted = 1;
          }
        });
      }
      return {
        ...state,
        logList
      };
    }

    /**
     * @description: 删除日志单
     * @param {number[]} ids 删除的ID列表
     */
    case DELETE_LOG_ITEM: {
      return {
        ...state,
        logList: delItemByIdArray(action.ids, state.logList)
      };
    }

    default:
      console.log('untouched', action);
      return state;
  }
};
